//
//  TotalController.swift
//  account
//
//  Created by Qingke on 16/5/3.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit
import CoreData

class TotalController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var toolBar: UIToolbar!
    var appDel: AppDelegate!
    var context: NSManagedObjectContext!
    var iconNames = ["生日","工作","娱乐","其他"]
    var result = []
    var dataModel : DataModel!
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        
        appDel = UIApplication.sharedApplication().delegate as! AppDelegate
        context = appDel.managedObjectContext
        
        // 将自定义的 消费类型进行的名字进行添加
        dataModel = appDel.dataModel
        for item in dataModel.items {
            iconNames.append(item.itemName ?? "没有")
        }
        
        addToolBarItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
    
    func addToolBarItem() {
        var items = [ UIBarButtonItem ]()
        for name in iconNames {
            let barItem = UIBarButtonItem(title: name, style: .Done, target: self, action: "fetchFromData:")
            items.append(barItem)
        }
        toolBar.setItems(items, animated: true)
    }
    
    func fetchFromData(sender: AnyObject) {
        if let buttonItem = sender as? UIBarButtonItem {
            let item = buttonItem.title ?? "没有"
            searchByCoreData(item)
            
        }
    }
    
    func searchByCoreData( item: String )  {
        let fetchRequest = NSFetchRequest(entityName: "Account")
        fetchRequest.predicate = NSPredicate(format: "item == %@",item)
        //这里如果一次性加入在内存里面的话数据太多就不合适了，需要直接在数据中筛选结果啊？
        do {
            result = try context.executeFetchRequest(fetchRequest) as! [AccountModel]
        } catch {
            fatalError("Failed to fetch employees: \(error)")
        }
//        result = try! context.executeFetchRequest(fetchRequest)
//        print(result.count)
        tableView.reloadData()
    }
    @IBAction func back(sender: UIBarButtonItem) {
        dismissViewControllerAnimated(true, completion: nil)
    }

}
extension TotalController: UITableViewDelegate, UITableViewDataSource{
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return result.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell")
        let account = result[indexPath.row] as! AccountModel
        cell!.accessoryType = .None
        cell!.textLabel?.text = account.item
        cell!.detailTextLabel?.text = String (account.number ?? 0.0)
        return cell!
    }

    
}
